<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Site extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }
    
    function index($msg = "")
    {
        $this->agenda(0, $msg);
    }
    
    function agenda($page = 0, $msg="")
    {
        $this->load->model('site_model');
        
        $data['horarios'] = $this->site_model->getHorarios();
        
        $arr_agenda = array();
        foreach ($data['horarios'] as $dados) 
        {
            $arr_agenda[$dados->horario][0] = $this->site_model->getAgenda($dados->horario, 0);
            $arr_agenda[$dados->horario][1] = $this->site_model->getAgenda($dados->horario, 1);
            $arr_agenda[$dados->horario][2] = $this->site_model->getAgenda($dados->horario, 2);
            $arr_agenda[$dados->horario][3] = $this->site_model->getAgenda($dados->horario, 3);
            $arr_agenda[$dados->horario][4] = $this->site_model->getAgenda($dados->horario, 4);
            $arr_agenda[$dados->horario][5] = $this->site_model->getAgenda($dados->horario, 5);
            $arr_agenda[$dados->horario][6] = $this->site_model->getAgenda($dados->horario, 6);
        }
        $data['mensagem'] = $msg;
        $data['agenda'] = $arr_agenda;
        $data['semana'] = $page;
        $this->load->view("site/header");
        $this->load->view("site/horarios", $data);
    }
    
    function agendar($horario, $especialidade, $diaMes)
    {
        $objSearch = null;
		
		$objSearch->groupOp = "AND";
		$objSearch->rules[0]->field = "id";
		$objSearch->rules[0]->op = "eq";
		$objSearch->rules[0]->data = $horario;
		
		$data['horario'] = $this->generic_model->getByFilter($objSearch, "horarios");
		
        $objSearchEsp = null;
		
		$objSearchEsp->groupOp = "AND";
		$objSearchEsp->rules[0]->field = "id";
		$objSearchEsp->rules[0]->op = "eq";
		$objSearchEsp->rules[0]->data = $especialidade;
		$data['especialidades'] = $this->generic_model->getByFilter($objSearchEsp, "especialidades");
		$data['data'] = $diaMes;
		$dt = explode("-",$diaMes);
		switch ($dt[1]) 
		{
			case "01":
			    $mes = "Janeiro";
			break;
			case "02":
			    $mes = "Fevereiro";
			break;
			case "03":
			    $mes = "Mar&ccedil;o";
			break;
			case "04":
			    $mes = "Abril";
			break;
			case "05":
			    $mes = "Maio";
			break;
			case "06":
			    $mes = "Junho";
			break;
			case "07":
			    $mes = "Julho";
			break;
			case "08":
			    $mes = "Agosto";
			break;
			case "09":
			    $mes = "Setembro";
			break;
			case "10":
			    $mes = "Outubro";
			break;
			case "11":
			    $mes = "Novembro";
			break;
			case "12":
			    $mes = "Dezembro";
			break;
		}
		$data['diaMes'] = $dt[0]." de ".$mes." de ".date('Y');
		foreach ($data['horario'] as $dados) 
		{
		    $this->load->model('site_model');
		    $data['medicos'] = $this->site_model->getMedicos($dados->id_dias_semana_fk, $dados->horario, $especialidade);

            $objSearchDia = null;
    		
    		$objSearchDia->groupOp = "AND";
    		$objSearchDia->rules[0]->field = "id";
    		$objSearchDia->rules[0]->op = "eq";
    		$objSearchDia->rules[0]->data = $dados->id_dias_semana_fk;
		    
		    $data['dia_semana'] = $this->generic_model->getByFilter($objSearchDia, "dias_semana");	
		}
		
        $data['estados'] = listEstados();
        $this->load->view("site/header");
        $this->load->view("site/agendar",$data);
    }
    
    function confirmar()
    {
        $action = $this->input->post('hid_oper');
        
        switch ($action) 
        {
        	case "reg":
        	    $config = array(
						array(
							'field' => "emailCad",
							'label' => "E-mail",
							'rules' => "trim|required|min_length[5]|max_length[45]|valid_email|xss_clean"
						),
        	            array(
							'field' => "medico",
							'label' => "M&eacute;dico",
							'rules' => "trim|required|integer|xss_clean"
						)
        	    );
        	    break;
        	
        	case "cad":
			    $config = array(
						array(
							'field' => "nome",
							'label' => "Nome",
							'rules' => "trim|required|min_length[5]|max_length[150]|xss_clean"
						),
						array(
							'field' => "endereco",
							'label' => "Endere&ccedil;o",
							'rules' => "trim|required|min_length[5]|max_length[150]|xss_clean"
						),
						array(
							'field' => "bairro",
							'label' => "Bairro",
							'rules' => "trim|required|min_length[3]|max_length[150]|xss_clean"
						),
						array(
							'field' => "numero",
							'label' => "N&uacute;mero",
							'rules' => "trim|required|min_length[1]|max_length[10]|xss_clean"
						),
						array(
							'field' => "cidade",
							'label' => "Cidade",
							'rules' => "trim|required|min_length[5]|max_length[100]|xss_clean"
						),
						array(
							'field' => "uf",
							'label' => "UF",
							'rules' => "trim|required|min_length[2]|max_length[2]|alpha|xss_clean"
						),
						array(
							'field' => "complemento",
							'label' => "Complemento",
							'rules' => "trim|max_length[255]|xss_clean"
						),
						array(
							'field' => "cep",
							'label' => "CEP",
							'rules' => "trim|required|min_length[9]|max_length[9]|alpha_dash|xss_clean"
						),
						array(
							'field' => "email",
							'label' => "E-mail",
							'rules' => "trim|required|min_length[5]|max_length[45]|valid_email|xss_clean|callback_email_check"
						),
						array(
							'field' => "telefone",
							'label' => "Telefone",
							'rules' => "trim|max_length[45]|xss_clean"
						),
						array(
							'field' => "celular",
							'label' => "Celular",
							'rules' => "trim|max_length[45]|xss_clean"
						),
						array(
							'field' => "medico",
							'label' => "M&eacute;dico",
							'rules' => "trim|required|integer|xss_clean"
						)
					);        	
        	    break;
            }
        $this->form_validation->set_rules($config);
		
		$this->form_validation->set_error_delimiters('<li>','</li>');

		if ($this->form_validation->run() == FALSE)
		{
			echo "err#".validation_errors();
		}
		else
		{
		    $dt = explode("-", $this->input->post('data_consulta'));
		    $data['id_medicos_fk'] = $this->input->post('medico');
		    $data['id_dias_semana_fk'] = $this->input->post('dia_semana');
		    $data['data_consulta'] = date('Y')."-".$dt[1]."-".$dt[0];
		    $data['horario'] = $this->input->post('horario');
            switch ($action) {
            	case "reg":
                    $objSearch = null;
            		
            		$objSearch->groupOp = "AND";
            		$objSearch->rules[0]->field = "email";
            		$objSearch->rules[0]->op = "eq";
            		$objSearch->rules[0]->data = $this->input->post('emailCad');
            		
            		$paciente = $this->generic_model->getByFilter($objSearch, "pacientes");

            		if (!is_null($paciente) && !empty($paciente))
            		{
                		$data['id_pacientes_fk'] = $paciente[0]->id;
                		
                		if ($this->generic_model->insert($data, "agenda"))
    					{
    					    echo "oks#Agendamento realizado com sucesso!";
    					}
    					else 
    					{
    						echo "err#Erro no agendamento!";
    					}				
            		}
            		else 
            		{
            		    echo "err#E-mail n&atilde;o cadastrado!";
            		}
            	    break;
            	
            	case "cad":
            	    $paciente['nome'] = strtoupper($this->input->post('nome'));
			        $paciente['endereco'] = strtoupper($this->input->post('endereco'));
			        $paciente['numero'] = $this->input->post('numero');
			        $paciente['bairro'] = strtoupper($this->input->post('bairro'));
			        $paciente['cidade'] = strtoupper($this->input->post('cidade'));
			        $paciente['cep'] = $this->input->post('cep');
			        $paciente['uf'] = strtoupper($this->input->post('uf'));
			        $paciente['complemento'] = strtoupper($this->input->post('complemento'));
			        $paciente['email'] = strtolower($this->input->post('email'));
			        $paciente['tel_residencia'] = $this->input->post('telefone');
			        $paciente['tel_celular'] = $this->input->post('celular');
            	    
            		if ($this->generic_model->insert($paciente, "pacientes"))
					{
					    $data['id_pacientes_fk'] = $this->generic_model->getLastId();
					    
                		if ($this->generic_model->insert($data, "agenda"))
    					{
					        echo "oks#Agendamento realizado com sucesso!";
    					}
    					else 
    					{
						    echo "err#Erro no agendamento!";
    					}				
				    }
					else 
					{
						echo "err#Erro no cadastro!";
					}				
			        
            	    break;
            }    
		}
    }
    
    function email_check($email)
	{
        $objSearch = null;
		
		$objSearch->groupOp = "AND";
		$objSearch->rules[0]->field = "email";
		$objSearch->rules[0]->op = "eq";
		$objSearch->rules[0]->data = $email;
	    		
		$result = $this->generic_model->count($objSearch, "pacientes");
		
		if ($result > 0)
		{
			$this->form_validation->set_message('email_check', "E-mail j&aacute; cadastrado!");
			return FALSE;	
		}
		else
		{
			return TRUE;
		}
	}
    
}